// 使用统一配置入口模式导入所有依赖
const pageHelper = require('../../../../../../helpers/page_helper.js');
const { projectsConfig } = require('../../../../../../config/module_config.js');
const AdminBiz = require('../../../../store/admin_biz_config.js');
const pathResolver = require('../../../../config/path_resolver.js');

// 引入MobX绑定
const { createStoreBindings } = require('mobx-miniprogram-bindings');
// 导入adminStore
const { adminStore } = require('../../../../config/store_config.js');
// 导入AdminNewsService
const AdminNewsService = require('../../../../services/admin/news_service.js');

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false,
		isAdmin: true,
		dataList: null,
		NEWS_NAME: '',
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		// 创建MobX绑定
		this.storeBindings = createStoreBindings(this, {
			store: adminStore,
			fields: ['loading'],
			actions: ['isAdmin']
		});
		
		// 检查权限 - 使用导入的AdminBiz
		if (!this.isAdmin()) return;

		wx.setNavigationBarTitle({
			title: projectsConfig.NEWS_NAME + '-管理',
		});
		this.setData({
			NEWS_NAME: projectsConfig.NEWS_NAME
		});

		//设置搜索菜单
		this._getSearchMenu();
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		// 不再需要路径调试
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: async function () { 
		await this._loadList();
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		// 清理MobX绑定
		this.storeBindings.destroyStoreBindings();
	},

	url: async function (e) {
		pageHelper.url(e, this);
	},

	bindCommListCmpt: function (e) {
		pageHelper.commListListener(this, e);
	},

	/** 
	 * 加载数据列表
	 */
	_loadList: async function () {
		if (!this.isAdmin()) return;

		try {
			const result = await AdminNewsService.getNewsList({
				search: '',
				sortType: '',
				sortVal: '',
				orderBy: {
					'NEWS_ORDER': 'asc',
					'NEWS_ADD_TIME': 'desc'
				},
				whereEx: {},
				page: 1,
				size: 20,
				isTotal: true
			});

			this.setData({
				dataList: result,
				isLoad: true
			});
		} catch (error) {
			console.error('获取新闻列表失败', error);
			this.setData({
				isLoad: true
			});
		}
	},

	_setSort: async function (e) {
		if (!this.isAdmin()) return;
		let id = e.currentTarget.dataset.id;
		let sort = e.currentTarget.dataset.sort;
		if (!id) return;

		try {
			const result = await AdminNewsService.updateNewsSort(id, sort);
			if (result && result.code == 200) {
				pageHelper.modifyListNode(id, this.data.dataList.list, 'NEWS_ORDER', sort);
				this.setData({
					dataList: this.data.dataList
				});
				pageHelper.showSuccToast('设置成功');
			}
		} catch (e) {
			console.log(e);
		}
	},

	_setVouch: async function (e) {
		if (!this.isAdmin()) return;

		let id = pageHelper.dataset(e, 'id');
		let vouch = pageHelper.dataset(e, 'vouch');
		if (!id) return;

		try {
			const result = await AdminNewsService.updateNewsVouch(id, vouch);
			if (result && result.code == 200) {
				pageHelper.modifyListNode(id, this.data.dataList.list, 'NEWS_VOUCH', vouch);
				this.setData({
					dataList: this.data.dataList
				});
				pageHelper.showSuccToast('设置成功');
			}
		} catch (err) {
			console.log(err);
		}
	},

	_del: async function (e) {
		if (!this.isAdmin()) return;
		let id = pageHelper.dataset(e, 'id');

		let callback = async () => {
			try {
				const result = await AdminNewsService.deleteNews(id);
				if (result && result.code == 200) {
					pageHelper.delListNode(id, this.data.dataList.list, '_id');
					this.data.dataList.total--;
					this.setData({
						dataList: this.data.dataList
					});
					pageHelper.showSuccToast('删除成功');
				}
			} catch (e) {
				console.log(e);
			}
		}
		pageHelper.showConfirm('确认删除？删除不可恢复', callback);
	},

	bindMoreTap: async function (e) {
		if (!this.isAdmin()) return;
		let idx = pageHelper.dataset(e, 'idx');

		let order = this.data.dataList.list[idx].NEWS_ORDER;
		let orderDesc = (order == 0) ? '取消置顶' : '置顶';

		let vouch = this.data.dataList.list[idx].NEWS_VOUCH;
		let vouchDesc = (vouch == 0) ? '推荐到首页' : '取消首页推荐';

		let itemList = ['预览', orderDesc, vouchDesc, '生成专属二维码'];

		wx.showActionSheet({
			itemList,
			success: async res => {
				switch (res.tapIndex) {
					case 0: { //预览
						let id = pageHelper.dataset(e, 'id');
						wx.navigateTo({
							url: '../../../news/detail/news_detail?id=' + id,
						});
						break;
					}
					case 1: { //置顶 
						let sort = (order == 0) ? 9999 : 0;
						e.currentTarget.dataset['sort'] = sort;
						await this._setSort(e);
						break;
					}
					case 2: { //上首页 
						vouch = (vouch == 0) ? 1 : 0;
						e.currentTarget.dataset['vouch'] = vouch;
						await this._setVouch(e);
						break;
					}
					case 3: { //二维码 
						let title = encodeURIComponent(pageHelper.dataset(e, 'title'));
						let qr = encodeURIComponent(pageHelper.dataset(e, 'qr'));
						wx.navigateTo({
							url: `../../setup/qr/admin_setup_qr?title=${title}&qr=${qr}`,
						})
						break;
					}
				}
			},
			fail: function (res) { }
		})
	},

	bindStatusMoreTap: async function (e) {
		if (!this.isAdmin()) return;
		let itemList = ['启用', '停用 (不可见)', '删除'];
		wx.showActionSheet({
			itemList,
			success: async res => {
				switch (res.tapIndex) {
					case 0: { //启用
						e.currentTarget.dataset['status'] = 1;
						await this._setStatus(e);
						break;
					}
					case 1: { //停止 
						e.currentTarget.dataset['status'] = 0;
						await this._setStatus(e);
						break;
					}
					case 2: { //删除
						await this._del(e);
						break;
					}
				}
			},
			fail: function (res) { }
		})
	},

	_setStatus: async function (e) {
		if (!this.isAdmin()) return;
		let id = pageHelper.dataset(e, 'id');
		let status = Number(pageHelper.dataset(e, 'status'));

		try {
			const result = await AdminNewsService.updateNewsStatus(id, status);
			if (result && result.code == 200) {
				pageHelper.modifyListNode(id, this.data.dataList.list, 'NEWS_STATUS', status, '_id');
				this.setData({
					dataList: this.data.dataList
				});
				pageHelper.showSuccToast('设置成功');
			}
		} catch (err) {
			console.log(err);
		}
	},

	_getSearchMenu: function () {
		let cateList = AdminNewsService.getCateList();

		let sortItems = [
			{ label: '全部', type: '', value: '' }
		];

		// 添加分类
		if (cateList && cateList.length > 1) {
			for (let k = 0; k < cateList.length; k++) {
				sortItems.push({
					label: cateList[k].title,
					type: 'cateId',
					value: cateList[k].id
				})
			}
		}

		let sortMenus = [
			{ label: '全部', type: '', value: '' },
			{ label: '正常', type: 'status', value: 1 },
			{ label: '停用', type: 'status', value: 0 },
			{ label: '首页推荐', type: 'vouch', value: 1 }
		];

		this.setData({
			search: '',
			cateIdOptions: cateList,
			sortItems,
			sortMenus
		})
	}
});